﻿using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using QuickGet.Core.Models;
using QuickGet.Core.Services;
using QuickGet.Core.Stores;

namespace QuickGet.Endpoints
{
    public static class InstalledPackageEndpoints
    {
        public static IEndpointRouteBuilder MapInstalledPackageEndpoints(this IEndpointRouteBuilder endpoints)
        {
            var group = endpoints.MapGroup("/installed-package").WithTags("InstalledPackage");

            group.MapGet("/versions", GetVersions).WithName(nameof(GetVersions));
            group.MapGet("/list", GetList).WithName(nameof(GetList));

            return endpoints;
        }

        public static async Task<Ok<DownloadFileResult>> GetDownloadUrl(
            [FromQuery] string id, [FromQuery] string version,
            [FromServices] IPackageStore store,
            [FromServices] IFileDownloadService downloadService,
            [FromServices] IOperationCancellation operationCancellation)
        {
            var filePath = await store.GetPackageDownloadPathAsync(id, version, operationCancellation.Token);
            var token = await downloadService.CreateDownloadTokenAsync(filePath);
            var found = string.IsNullOrWhiteSpace(token) == false;
            var downloadUrl = await downloadService.GetFileDownloadUrlAsync(token);
            var fileName = Path.GetFileName(filePath);

            return TypedResults.Ok(new DownloadFileResult(found, token, downloadUrl, fileName));
        }

        public static async Task<Ok<List<PackageVersionInfo>>> GetVersions(
            [FromQuery] string packageId,
            [FromServices] IPackageStore store,
            [FromServices] IOperationCancellation operationCancellation)
        {
            var versions = await store.GetDownloadedVersionsAsync(packageId, operationCancellation.Token);

            return TypedResults.Ok(versions);
        }

        public static async Task<Ok<List<PackageInfo>>> GetList(
            [FromServices] IPackageStore store,
            [FromServices] IOperationCancellation operationCancellation)
        {
            var packages = await store.GetListAsync(operationCancellation.Token);

            return TypedResults.Ok(packages);
        }
    }
}
